import store from '@/store'
import { Toast } from "vant"

/**
 * 遍历对象的每个属性,并允许传入一个回调函数来处理该属性
 * @param {*} obj 待遍历对象
 * @param {*} callback 仅支持一个参数,为当前变量的对象的属性名
 */
function eachProp(obj, callback){
    Object.keys(obj).forEach(callback)
}

/**
 * 判断对象是否为空
 * @param {*} target
 */
function isNull (target){
    return target === undefined || target === null;
}

export const reftoken = async (that, app) => {

    let globalData = store.getters.globalData
    let params = {
        grant_type: "meeting_token", // refresh_token
        refresh_token: globalData.access_token,
        meetingNum: globalData.meetingNum
    }
    const res = await that.$getAPIs(that, params, "获取token","apis", "seachToken")
    if (!res){
        Toast({
            message: "权限校验失败，请重新登录！",
            duration: 3000,
            onClose: () => {
                setTimeout(()=>{
                    that.$router.replace( '/')
                }, 3000)
            }});
        return false
    };
    setTimeout(() => {
        reftoken(that)
    // }, 2000)
    }, 600000)
    const {access_token, token_type} = res
    that.$store.commit("UPDATE_GLOBAL", {key: "access_token", val: token_type + " " + access_token})
}

// 创建当前时间
export const now = function(format = 'YYYY-MM-DD HH:mm:ss') {
    const nowTime = new Date();
    return formatTime(nowTime, format);
}

// 日期格式化
const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
    let transDate = format;
    const schema = {
        'M+': date.getMonth() + 1,
        'D+': date.getDate(),
        'H+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds(),
    };
    if (/(Y+)/.test(transDate)) {
        transDate = transDate.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length));
    }

    eachProp(schema, (el) => {
        if (new RegExp(`(${el})`).test(transDate)) {
            transDate = transDate.replace(RegExp.$1, (RegExp.$1.length === 1) ? (schema[el]) : ((`00${schema[el]}`).substr((`${schema[el]}`).length)));
        }
    });
    return transDate;
}

export {
    eachProp,
    isNull
}